import java.util.Arrays;

public class Text {
    public static void main(String[] args) {
        int[] array = {32,45,6,16,73,49,12,49};
        //countSort(array);
        mergeSortNor(array);
        System.out.println(Arrays.toString(array));
    }
    // 归并排序---递归
    public static void mergeSort(int[] array){
        mergeFunc(array,0,array.length-1);
    }
    public static void mergeFunc(int[] array,int left,int right) {
        if(left >= right){
            return;
        }
        int mid = (left+right)/2;
        mergeFunc(array,left,mid);
        mergeFunc(array,mid+1,right);
        merge(array,left,right,mid);
    }

    public static void merge(int[] array,int start,int end,int mid) {
        int s1 = start;
        int s2 = mid+1;
        int[] tmp = new int[end-start+1];
        int k = 0;
        while(s1 <= mid && s2 <= end) {
            if(array[s1] < array[s2]){
                tmp[k]=array[s1];
                s1++;
                k++;
            }else{
                tmp[k]=array[s2];
                s2++;
                k++;
            }
        }
        while(s1 <= mid){
            tmp[k]=array[s1];
            s1++;
            k++;
        }
        while (s2 <= end){
            tmp[k]=array[s2];
            s2++;
            k++;
        }
        for (int i = 0; i < tmp.length; i++) {
            array[i+start] = tmp[i];
        }
    }

// 归并排序---非递归
    public static void mergeSortNor(int[] array){
        int gap = 1;
        while(gap < array.length){
            for (int i = 0; i < array.length; i+=gap*2) {
                int left=i;
                int mid=i+gap-1;
                if(mid >= array.length){
                    mid = array.length-1;
                }
                int right=mid+gap;
                if(right >= array.length){
                    right = array.length-1;
                }
                merge(array,left,right,mid);
            }
            gap *=2;
        }
    }

// 计数排序
    public static void countSort(int[] array){
        int max = 0;
        int min = 100;
        for(int i=0;i<array.length;i++){
            if(array[i]>max){
                max = array[i];
            }
            if(array[i]<min){
                min = array[i];
            }
        }
        int[] tmp = new int[max-min+1];
        for(int i=0;i<array.length;i++){
            tmp[array[i]-min]++;
        }
        int[] ret = new int[array.length];
        int k =0;
        for (int i = 0; i < tmp.length; i++) {
            while(tmp[i] > 0){
                ret[k++] = i+min;
                tmp[i]--;
            }
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = ret[i];
        }
    }
}
